package tang.server;

/**
 * @author Tang
 * @classname QuorumPeer
 * @description [  ]
 * @date 2021/3/7 10:49
 */
public class QuorumPeer extends Thread{

    private NioServerCnxnFactory nioServerCnxnFactory;

    private boolean running = true;

    private ServerState state = ServerState.FOLLOWING;

    enum ServerState {
        LOOKING,FOLLOWING,LEADING,OBSERVING;
    }

    public Follower follower;
    public Leader leader;
    public Observer observer;

    public void init() {
        follower = new Follower();
        leader = new Leader();
        observer = new Observer();
    }

    @Override
    public void run() {
        /**
         * main loop
         */
        while (running) {
            switch (getServerState()) {
                case LOOKING:
                    System.out.println("LOOKING...");
                    break;
                case LEADING:
                    leader.leader();
                    break;
                case FOLLOWING:
                    follower.followerLeader();
                    break;
                case OBSERVING:
                    observer.observerLeader();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public synchronized void start() {
        // 1.加载快照到本地内存
        loadDb();
        // 2.启动接收命令请求的线程
        new Thread(nioServerCnxnFactory).start();
        // 3.启动领导者选举  改变 state
        startLeaderElection();
        // 4.启动当前服务器
        super.start();
    }

    private void loadDb() {

    }

    private void startLeaderElection() {

    }

    public ServerState getServerState() {
        return this.state;
    }


    public void setSetverCnxnFactory(NioServerCnxnFactory nioServerCnxnFactory) {
        this.nioServerCnxnFactory = nioServerCnxnFactory;
    }
}